package com.binaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class AverageofLevelsinBinaryTree0209_637 {
    public List<Double> averageOfLevels(TreeNode root) {
        if(root == null) return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        List<Double> res = new ArrayList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            int len = queue.size();
            int size = queue.size();
            double sum = 0;

            while (len > 0){
                TreeNode node = queue.poll();
                sum += node.val;
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
                len --;
            }
            res.add( sum / size);
        }
        return res;
    }
}
